import logging
from io import BytesIO
from imghdr import what as img_type
import httpx

def get_img(url, img_stem):
    response = httpx.get(
        url,
        headers={
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0",
            "Accept-Encoding": "gzip, deflate, br",
            "Referer": "https://www.toutiao.com",
        },
    )
    if response.is_success:
        img_content = response.content
        extension = img_type(BytesIO(img_content))
        img_name = "{}.{}".format(img_stem, extension)
        return {
            "name": img_name,
            "content": img_content,
            "extension": extension,
        }
    else:
        logging.warning(img_stem + "下载失败")
        return None
    
